#include "histogram.h"
#include <string.h>

histogram * his_init(int width, int size)
{
	histogram * his;
	his = (histogram *)malloc(sizeof(histogram));
	his->data = (int *)malloc(size * sizeof(int));
	memset(his->data, 0, size);
	his->total_key_num = 0;
	his->size = size;
	his->width = width;
	if (his)
		return his;
	return NULL;
}

void his_insert(histogram * his, int key)
{
	his->total_key_num++;
	int index = (int)(key / his->width);
	if(index > his->size)
		return;
	his->data[index]++;
}

double his_range_ratio(histogram * his, int left, int right)
{
	if (left > right)
		return 0.0;
	double sum = 0;
	int leftindex = (int)(left / his->width), rightindex = (int)(right / his->width);
	int leftmod = left % his->width, rightmod = right % his->width;
	for(int i = leftindex + 1; i < rightindex && i < his->size; i++)
		sum += his->data[i];
	sum += ((double)(his->width - leftmod)) / (double)(his->width) * (double)(his->data[leftindex]);
	sum += ((double)rightmod / (double)(his->width)) * (double) (his->data[rightindex]);
	return sum / (double)(his->total_key_num);
}
